package com.ruoyi.user.controller.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SpffComments;
import com.ruoyi.system.service.ISpffCommentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 评论Controller
 * 
 * @author xjj
 * @date 2025-09-11
 */
@RestController
@RequestMapping("/userApi/comments")
public class USpffCommentsController extends BaseController
{
    @Autowired
    private ISpffCommentsService spffCommentsService;

    /**
     * 查询评论列表（统一接口：一级和二级评论）
     * parentId=0 查询一级评论（支持分页）
     * parentId>0 查询指定评论的回复（不分页）
     */
    @GetMapping("/list")
    public AjaxResult list(SpffComments spffComments)
    {
        try {
            // 只查询正常状态的评论
            spffComments.setStatus(1);
            
            // 默认查询一级评论
            if (spffComments.getParentId() == null) {
                spffComments.setParentId(0L);
            }
            
            if (spffComments.getParentId() == 0L) {
                // 一级评论：支持分页
                startPage();
                List<SpffComments> list = spffCommentsService.selectSpffCommentsList(spffComments);
                return success(getDataTable(list));
            } else {
                // 二级评论：不分页，一次性返回所有回复
                List<SpffComments> replies = spffCommentsService.selectSpffCommentsList(spffComments);
                return success(replies);
            }
        } catch (Exception e) {
            logger.error("获取评论列表失败：" + e.getMessage());
            return error("获取评论列表失败：" + e.getMessage());
        }
    }

    /**
     * 导出评论列表
     */
    @PreAuthorize("@ss.hasPermi('system:comments:export')")
    @Log(title = "评论", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SpffComments spffComments)
    {
        List<SpffComments> list = spffCommentsService.selectSpffCommentsList(spffComments);
        ExcelUtil<SpffComments> util = new ExcelUtil<SpffComments>(SpffComments.class);
        util.exportExcel(response, list, "评论数据");
    }

    /**
     * 获取评论详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:comments:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(spffCommentsService.selectSpffCommentsById(id));
    }

    /**
     * 发布评论（用户端）
     */
    @PostMapping
    public AjaxResult add(@RequestBody SpffComments spffComments)
    {
        try {
            // 获取当前登录用户ID
            Long userId = com.ruoyi.common.utils.SecurityUtils.getUserId();
            spffComments.setUserId(userId);
            
            // 设置默认值
            spffComments.setLikeCount(0L);
            spffComments.setReplyCount(0L);
            spffComments.setIsTop(0);
            spffComments.setStatus(1);
            spffComments.setCreatedAt(new java.util.Date());
            
            // 如果是回复评论，更新父评论的回复数
            if (spffComments.getParentId() != null && spffComments.getParentId() > 0) {
                spffCommentsService.incrementReplyCount(spffComments.getParentId());
            }
            
            int result = spffCommentsService.insertSpffComments(spffComments);
            return result > 0 ? success("评论发布成功") : error("评论发布失败");
        } catch (Exception e) {
            logger.error("发布评论失败：" + e.getMessage());
            return error("发布评论失败：" + e.getMessage());
        }
    }

    /**
     * 修改评论
     */
    @PreAuthorize("@ss.hasPermi('system:comments:edit')")
    @Log(title = "评论", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SpffComments spffComments)
    {
        return toAjax(spffCommentsService.updateSpffComments(spffComments));
    }

    /**
     * 删除评论（只能删除自己的评论）
     */
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        try {
            Long userId = com.ruoyi.common.utils.SecurityUtils.getUserId();
            SpffComments comment = spffCommentsService.selectSpffCommentsById(id);
            
            if (comment == null) {
                return error("评论不存在");
            }
            
            if (!comment.getUserId().equals(userId)) {
                return error("只能删除自己的评论");
            }
            
            // 逻辑删除，设置状态为0
            comment.setStatus(0);
            comment.setUpdatedAt(new java.util.Date());
            
            return toAjax(spffCommentsService.updateSpffComments(comment));
        } catch (Exception e) {
            return error("删除评论失败：" + e.getMessage());
        }
    }


    /**
     * 点赞/取消点赞评论
     */
    @PostMapping("/like/{commentId}")
    public AjaxResult toggleLike(@PathVariable Long commentId)
    {
        try {
            Long userId = com.ruoyi.common.utils.SecurityUtils.getUserId();
            int result = spffCommentsService.toggleCommentLike(commentId, userId);
            boolean isLiked = result == 1;
            return success(isLiked);
        } catch (Exception e) {
            return error("操作失败：" + e.getMessage());
        }
    }

    /**
     * 获取评论点赞状态
     */
    @GetMapping("/like-status/{commentId}")
    public AjaxResult getLikeStatus(@PathVariable Long commentId)
    {
        try {
            Long userId = com.ruoyi.common.utils.SecurityUtils.getUserId();
            boolean isLiked = spffCommentsService.isUserLikedComment(commentId, userId);
            return success(isLiked);
        } catch (Exception e) {
            return error("获取点赞状态失败：" + e.getMessage());
        }
    }
}
